﻿using System.Collections.Concurrent;

namespace Core
{
    public class Buffer
    {
        public byte[] data = new byte[Config.BUFF_SIZE];
        public int dataLength;
        public int Remain { get { return Config.BUFF_SIZE - dataLength; } }

        public int receiveMessageLength;

        public void Clear()
        {
            dataLength = 0;
            receiveMessageLength = 0;
        }
    }

    public class MessageBuffer
    {
        public byte[] buffer = new byte[Config.MAX_MESSAGE_SIZE];
        public int messageLength;

        public static ConcurrentStack<MessageBuffer> pools = new ConcurrentStack<MessageBuffer>();

        public static MessageBuffer Pop()
        {
            if (pools.TryPop(out var buffer))
            {
                return buffer;
            }
            else
            {
                return new MessageBuffer();
            }
        }

        public static void Push(MessageBuffer messageBuffer)
        {
            // 太多了，不回收
            if (pools.Count >= 1000)
                return;
            messageBuffer.messageLength = 0;
            pools.Push(messageBuffer);
        }
    }
}
